////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;
import cc.telecomdigital.tdstock.adapter.ShortSellListItemAdapter;
import cc.telecomdigital.tdstock.adapter.ShortSellViewHolder;

/**
 * 
 * @author haibo
 * 
 *  for  list item on ShortSell
 *
 */
public class ShortSellContentActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String			TAG			= ShortSellContentActivity.class.getSimpleName();

	private static final long				START_ID	= 90000l;

	private ListView						_listView;
	private Button							_toolBtnReturn;
	private TextView						_topBarTitle;

	private static int						fromMonth;
	private static int						fromDay;
	private static int						toMonth;
	private static int						toDay;

	private static ShortSellListItemAdapter		_shortSellAdapter;
	private static List<ShortSellViewHolder>	_shortSellList;

	private SharedPreferences				_prefsStockCode;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_shortsell_content);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(), ShortSellActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(ShortSellActivity.class, intent);
			}
		});

		_messageHandler = null; //this activity no need it.
		_topBarTitle = (TextView) findViewById(R.id.topbar_title);
		_listView = (ListView) findViewById(R.id.more_shortsell_list);

		_shortSellList = new ArrayList<ShortSellViewHolder>();
		_shortSellAdapter = new ShortSellListItemAdapter(LayoutInflater.from(this), _shortSellList);
		_listView.setAdapter(_shortSellAdapter);

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				if (position != -1 && _shortSellList.size() >= position + 1)
				{
					String stockCode = String
							.valueOf(Integer.parseInt(_shortSellList
									.get(position).item_name
									.split("[  ]")[0].trim()));
					_prefsStockCode = getSharedPreferences(
							CommonDefn.SYSTEM_CURRENT_SETTING,
							Context.MODE_PRIVATE);
					_prefsStockCode.edit().putString(
							CommonDefn.PREFERENCE_STOCK_CODE, stockCode)
							.commit();

					// BMP Mode  by ouyangzhihui 2011-10-13
					Class<? extends ActivityGroup_Framework>_cls = CurrentStockInfoActivity.class;
					if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
					{
						_cls = BMPCurrentStockInfoActivity.class;
					}
					
					Intent intent = new Intent(getApplicationContext(), _cls);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

					SwitchTabHostActivity(0, StockGroup.GetActivityGroupHostControl(), _cls,intent);
				}
			}
		});
	}

	private void updateData(List<String[]> result)
	{
		if(iTypeId == 0 || iTypeId == 1)
		{
			String timeStamp = result.get(0)[3].trim();
			fromMonth = Integer.parseInt(timeStamp.substring(4, 6));
			fromDay = Integer.parseInt(timeStamp.substring(6, 8));
		}
		else
		{
			String[] array = result.get(0);
			String fromDate = array[0].trim();
			String toDate = array[1].trim();
			
			fromMonth = Integer.parseInt(fromDate.substring(4, 6));
			fromDay = Integer.parseInt(fromDate.substring(6, 8));
			
			toMonth = Integer.parseInt(toDate.substring(4, 6));
			toDay = Integer.parseInt(toDate.substring(6, 8));
			
			result.remove(0);
		}
		
		_shortSellList.clear();
		int index = 0;
		long id = START_ID + _shortSellList.size();
		for (String[] array : result)
		{
			if (array[0] == null || array[0].length() < 1)
			{
				continue;
			}
			ShortSellViewHolder holder = new ShortSellViewHolder();
			holder.id = id + index;
			holder.item_name = String.format("%05d %s", Integer.parseInt(array[0]), array[1]);
			holder.item_value = array[2] == null ? CommonDefn.DEFAULT_FIELD_VALUE : array[2];
			_shortSellList.add(holder);
			index++;
		}
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		_listView.invalidateViews();		
	}
	
	private void resetContent()
	{
		_shortSellList.clear();
		_shortSellAdapter.notifyDataSetChanged();
	}
	
	private void resetTitle()
	{
		_topBarTitle.setText(""); //clear the title first, then waiting for update;
	}

	private void updateTitle()
	{
		int[] resourceIds = { R.string.more_shortsell_topbar_noon_title,
				R.string.more_shortsell_topbar_today_title,
				R.string.more_shortsell_topbar_last7days_title };
		
		int index = iTypeId;
		
		String title;
		if (index == 0 || index == 1)
		{
			title = this.getResources().getString(
					resourceIds[index],
					String.format("%02d", fromMonth),
					String.format("%02d", fromDay));
		}
		else
		{
			title = this.getResources().getString(
					resourceIds[index],
					String.format("%02d", fromMonth),
					String.format("%02d", fromDay),
					String.format("%02d", toMonth),
					String.format("%02d", toDay));
		}
		_topBarTitle.setText(title);
	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}
	
	static public int iTypeId = 0;
	
	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		resetTitle();
		resetContent();
		
		return HttpAppInfo.SendShortSellActivity(actContext, iTypeId, this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if(!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError+"("+iResult.MStatus+")");
			return;
		}
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				updateData(iResult.contentStores);
				
				_shortSellAdapter.notifyDataSetChanged();
				
				updateTitle();
			}
		};
		_messageHandler.post(runnable);
	}

}
